import 'package:flutter/material.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:xiecheng_lvyou/dao/home_dao.dart';
import 'package:xiecheng_lvyou/model/common_model.dart';
import 'package:xiecheng_lvyou/model/grid_nav_model.dart';
import 'package:xiecheng_lvyou/model/home_model.dart';
import 'package:xiecheng_lvyou/model/sales_box_model.dart';
import 'package:xiecheng_lvyou/pages/search_page.dart';
import 'package:xiecheng_lvyou/pages/speak_page.dart';
import 'package:xiecheng_lvyou/util/navigator_util.dart';
import 'package:xiecheng_lvyou/widget/grid_nav.dart';
import 'package:xiecheng_lvyou/widget/loading_container.dart';
import 'package:xiecheng_lvyou/widget/local_nav.dart';
import 'package:xiecheng_lvyou/widget/sales_box.dart';
import 'package:xiecheng_lvyou/widget/search_bar.dart';
import 'package:xiecheng_lvyou/widget/sub_nav.dart';
import 'package:xiecheng_lvyou/widget/webview.dart';

const appBarScrollOffset = 100;
const searchBarDefaultText = '网红打卡地 景点 酒店 美食';

class HomePage extends StatefulWidget {
  const HomePage({super.key});
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  double appBarAlpha = 0;
  List<CommonModel> localNavList = [];
  List<CommonModel> bannerList = [];
  List<CommonModel> subNavList = [];
  SalesBoxModel? salesBoxModel;
  GridNavModel? gridNavModel;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _handleRefesh();
  }

  Future<Null> _handleRefesh() async {
    // HomeDao.fetch().then((result) {
    //   setState(() {
    //     resultString = json.encode(result);
    //     debugPrint(resultString);
    //   });
    // }).catchError((e) {
    //   setState(() {
    //     resultString = json.toString();
    //     debugPrint(resultString);
    //   });
    // });

    try {
      HomeModel model = await HomeDao.fetch();
      debugPrint('吴斌');
      setState(() {
        if (model.localNavList != null) {
          localNavList = model.localNavList!;
          gridNavModel = model.gridNav!;
          subNavList = model.subNavList!;
          salesBoxModel = model.salesBox!;
          bannerList = model.bannerList!;
          _loading = false;
        }
      });
    } catch (e) {
      setState(() {
        debugPrint(e.toString());
        _loading = false;
      });
    }
    return null;
  }

  _onScroll(offset) {
    double alpha = offset / appBarScrollOffset;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
    // debugPrint('$appBarAlpha--吴斌');
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        backgroundColor: const Color(0xfff2f2f2),
        body: LoadingContainer(
            isLoading: _loading,
            child: Stack(
              children: [
                MediaQuery.removePadding(
                    context: context,
                    removeTop: true,
                    child: NotificationListener(
                      onNotification: (scrollNotification) {
                        if (scrollNotification is ScrollUpdateNotification &&
                            scrollNotification.depth == 0) {
                          //滚动且是列表滚动的时候
                          _onScroll(scrollNotification.metrics.pixels);
                        }
                        return true;
                      },
                      child: RefreshIndicator(
                          onRefresh: _handleRefesh, child: _listView),
                    )),
                _appBar
              ],
            )));
  }

  // bannar
  Widget get _swiperWidget {
    return Swiper(
      itemCount: bannerList.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            CommonModel model = bannerList[index];
            NavigatorUtil.push(
                context,
                WebView(
                  url: model.url,
                  title: model.title,
                  hideAppBar: model.hideAppBar,
                ));
          },
          child: Image.network(
            bannerList[index].icon ?? '',
            fit: BoxFit.fill,
          ),
        );
      },
      pagination: const SwiperPagination(),
      autoplay: true,
      onTap: (index) {},
    );
  }

  Widget get _banner {
    return SizedBox(
      height: 200,
      // alignment: Alignment.topCenter,
      child: _swiperWidget,
    );
  }

  Widget get _listView {
    return ListView(
      children: <Widget>[
        _banner,
        Padding(
            padding: const EdgeInsets.fromLTRB(7, 4, 7, 4),
            child: LocalNav(localNavList: localNavList)),
        Padding(
          padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: GridNav(gridNavModel: gridNavModel),
        ),
        Padding(
          padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SubNav(subNavList: subNavList),
        ),
        Padding(
            padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
            child: SalesBox(salesBox: salesBoxModel)),
      ],
    );
  }

  Widget get _appBar {
    return Column(
      children: [
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
                colors: [Color(0x66000000), Colors.transparent],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter),
          ),
          child: Container(
            padding: const EdgeInsets.fromLTRB(0, 24, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
              color: Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255),
            ),
            child: SearchBarNav(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: searchBarDefaultText,
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
          height: appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: const BoxDecoration(
              boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]),
        )
      ],
    );
  }

  _jumpToSpeak() {
    NavigatorUtil.push(context, const SpeakPage());
  }

  _jumpToSearch() {
    NavigatorUtil.push(
        context,
        const SearchPage(
          hint: searchBarDefaultText,
        ));
  }
}
